package com.awccis.common.controller;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class BaseUploadController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(BaseUploadController.class);

    public BaseUploadController() {
    }
    /**
     * 上传文件
     *
     * @param fileName      文件夹名称
     * @param request       请求
     * @param multipartFile 文件对象
     * @return {"imgPath": "/WEB-INF/upload/..........."}
     */
    public Map uploadFile(String fileName, HttpServletRequest request, MultipartFile multipartFile) {
        //文件名称会不会重复
        String newFileName = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        newFileName = sdf.format(new Date());

        Random r = new Random();
        for (int i = 0; i < 4; i++) {
            newFileName = newFileName + r.nextInt(10);
        }

        //获取文件的扩展名
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        if (fileName == null) {
            fileName = "img";
        }
        //图片的父级目录
        String basePath = "/var/tomcat/awccis/upload/";
        //图片文件所在路径
        String sonFileLocation = fileName + "/" + newFileName + suffix;
        //图片的相对路径
        String relativePath = sonFileLocation;
        //图片的完整路径
        //String fullPath = request.getServletContext().getRealPath("WEB-INF/upload/") + sonFileLocation;
        String fullPath = basePath + sonFileLocation;
        logger.info("完整路径：" + fullPath);
        File file = new File(fullPath);
        System.out.println(fullPath);
        try {
            file.createNewFile();
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            logger.warn("写入文件失败---" + e);
        }

        //图片的压缩路径
        String thumbnailPath = basePath + "thumbnail/" + sonFileLocation;
        try {
            Thumbnails.of(fullPath).size(144, 144).keepAspectRatio(true).toFile(thumbnailPath);
        } catch (IOException e) {
            logger.warn("压缩图片异常： " + e);
        }

        Map map = new HashMap(1);
        map.put("imgPath", relativePath);

        return map;
    }
}
